package cn.xz.xy.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import cn.xz.xy.R;


@SuppressLint("AppCompatCustomView")
public class XZTextView extends TextView {
    private String mDrawableName;
    public XZTextView(Context context) {
        super(context);
    }

    public XZTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public XZTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public XZTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);

    }
    private void init(AttributeSet attrs){
        TypedArray t = getContext().obtainStyledAttributes(attrs, R.styleable.XZTextView);
        if(t != null){
            mDrawableName = t.getString(R.styleable.XZTextView_xz_background);
            if (mDrawableName != null){
                setBackgroundResource(getResourceId(mDrawableName));
                t.recycle();
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    @Override
    public void setPressed(boolean pressed) {
        super.setPressed(pressed);
        if(pressed){
            setBackgroundResource(getResourceId(mDrawableName+"_1"));
        }else{
            setBackgroundResource(getResourceId(mDrawableName));
        }
    }

    @Override
    public void setFocusable(boolean focusable) {
        super.setFocusable(focusable);
        if (mDrawableName != null){
            if(focusable){
                setBackgroundResource(getResourceId(mDrawableName+"_1"));
            }else{
                setBackgroundResource(getResourceId(mDrawableName));
            }
        }
    }

    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        if(selected){
            setBackgroundResource(getResourceId(mDrawableName+"_1"));
        }else{
            setBackgroundResource(getResourceId(mDrawableName));
        }
    }
    /**
     * 根据图片名称获取图片的资源id的方法
     * @param imageName
     * @return
     */
    public int  getResourceId(String imageName){
        Context ctx=getContext();
        int resId = getResources().getIdentifier(imageName, "mipmap" , ctx.getPackageName());
        return resId;
    }

}
